import 'quill/dist/quill.snow.css'
import './editor.css'

import Quill from 'quill'
import config from '../../../common/config.js'
import store from '../../../store/index.js'
import g from '../../../common/g.js'
import audio from './audio.js'
import { Toast } from 'mint-ui'
import FileUpload from 'vue-upload-component'

export default {
  components: {
    FileUpload
  },
  props: {
    toolbaroptions: {
      type: [Array, String, String],
      default: function () {
        return [
          ['bold'],
          ['italic'],
          ['underline'],
          ['blockquote'],
          ['image'],
          [{'header': 1}],
          [{'header': 2}],
          [
            {'list': 'ordered'},
            {'list': 'bullet'}
          ],
          [{'align': []}],
          ['link']
        ]
      }
    },
    placeholder: {
      type: String,
      default: '请输入内容...'
    },
    typess: {
      type: String,
      default: 'answers'
    }
  },
  data: function () {
    return {
      editor: {},
      config: config,
      uploadShow: false,
      upnum: 0,
      files: [],
      uploadurl: config.upURI,
      multiple: true,
      uploadList: [],
      uploadNum: 0,
      refreshAuth: false,
      header: {Authorization: 'Bearer ' + store.getters.auth('jwt')},
      winheight: '140px',
      filelist: []
    }
  },
  mounted: function () {
    this.create()
  },
  methods: {
    create: function () {
      if (this.typess === 'articles') {
        this.winheight = (window.innerHeight - 225) + 'px'
      } else {
        this.winheight = window.innerHeight / 3 * 2 + 'px'
      }
      let that = this
      Quill.register(audio, true)
      let options = {
        modules: {
          toolbar: {
            container: this.toolbaroptions,
            handlers: {
              'image': function (value) {
                if (value) {
                  console.log(that.$refs.upload)
                  that.$refs.upload.$el.children[0].click()
                  // that.$refs.uploadfile.click()
                  // document.getElementById('uploadfile').click()
                } else {
                  that.editor.format('image', false)
                }
              }
            }
          }
        },
        placeholder: this.placeholder,
        scrollingContainer: '#ql-editor',
        theme: 'snow'
      }
      this.editor = new Quill(this.$refs.plEditor, options)
      this.editor.on('text-change', function (delta, oldDelta, source) {
        that.$emit('text-change', delta)
      })
    },
    inputFile (newFile, oldFile) {
      if (newFile && !oldFile) {
        // 添加文件
        this.addnum++
      }

      if (newFile && oldFile) {
        // 开始上传
        if (newFile.active !== oldFile.active) {
          console.log('Start upload', newFile.active, newFile)

          // 限定最小字节
          if (newFile.size >= 0 && newFile.size > 2 * 1024 * 1024) {
            newFile = this.$refs.upload.update(newFile, {error: 'size'})
            Toast({
              message: '图片最大不能超过2M',
              duration: 2000
            })
          }
        }

        // 上传进度
        if (newFile.progress !== oldFile.progress) {
          console.log('progress', newFile.progress, newFile)
        }

        // 上传错误
        if (newFile.error !== oldFile.error) {
          console.log('error', newFile.error, newFile)
          Toast({
            message: '第' + this.upnum + '张上传失败，原因是：' + newFile.error,
            duration: 2000
          })
        }

        // 上传成功
        if (newFile.success !== oldFile.success) {
          this.upnum++
          console.log('success', newFile.success, newFile)
          let imgMsg = JSON.parse(newFile.response)
          this.filelist.push({
            url: imgMsg.memo.fullName,
            title: '图片' + this.upnum
          })
          let length = this.editor.getSelection().index
          this.editor.insertEmbed(length, 'image', config.imgURI + imgMsg.memo.fullName)
          this.editor.setSelection(length + 2)
        }
      }

      if (!newFile && oldFile) {
        // 删除文件

        // 自动删除 服务器上的文件
        if (oldFile.success && oldFile.response.id) {
          // $.ajax({
          //   type: 'DELETE',
          //   url: '/file/delete?id=' + oldFile.response.id,
          // });
        }
      }
      // 自动上传
      if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
        if (!this.$refs.upload.active) {
          this.$refs.upload.active = true
        }
      }
    },
    uploadSuccess: function (response, file, fileList) {
      this.uploadList.push(file.uid)
      if (response.status === 400) {
        file.status = 'error'
        file.name += ' (上传失败)'

        let authErrors = ['auth_empty', 'auth_error', 'auth_refresh_error', 'auth_timeout']
        if (authErrors.indexOf(response.msg) >= 0 && this.refreshAuth === false) {
          if (response.msg !== 'auth_timeout') {
            store.dispatch('loginNeed')
          } else {
            this.refreshAuth = true
            g.refreshJwt(() => {
              this.refreshAuth = false
            })
          }
        }
      }

      if (this.uploadList.length === fileList.length) {
        this.uploadEnd(fileList)
      }
    },
    uploadError (err, file, fileList) {
      this.uploadList.push(file.uid)
      if (this.uploadList.length === fileList.length) {
        this.uploadEnd(fileList)
      }
      if (err) {
        console.log(err)
      }
    },
    uploadRemove: function (file, fileList) {
      this.uploadList = this.uploadList.filter((item) => item !== file.uid)
    },
    beforeUpload: function (file) {
      this.uploadShow = true
      const isLt2M = file.size / 1024 / 1024 < 2
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      if (!isLt2M) {
        this.$message.error(file.name + ' 大小超过了 2MB,只允许上传不超过2MB的图片')
        return
      }
      if (!isJPG && !isJPEG && !isPNG && !isGIF) {
        this.$message.error(file.name + ' 格式不是 JPG/JPEG/PNG/GIF 其中一种')
        return false
      }
    },
    uploadExceed: function (files) {
      this.$message.warning(`只能选择 10 个文件，本次选择了 ${files.length} 个文件`)
    },
    uploadEnd: function (fileList) {
      this.uploadList = []
      setTimeout(() => {
        this.$refs.upload.clearFiles()
        this.uploadShow = false
      }, 1000)

      for (let v in fileList) {
        let res = fileList[v]
        if (res.status === 'success') {
          let length = this.editor.getSelection().index
          this.editor.insertEmbed(length, 'image', config.imgURI + res.response.memo.fullName)
          this.editor.setSelection(length + 2)
        }
      }
    },
    getContent: function () {
      return this.editor.getContents()
    },
    setContent: function (content) {
      this.editor.setContents(content)
    },
    setFocus: function () {
      this.editor.focus()
    }
  },
  template: '<div class="kk-editor" :style="{height: winheight}"  ref="kkEditor">' +
  '<div ref="plEditor" ></div><div class="kk-editor-mask" v-show="uploadShow"><div class="kk-editor-uploader" >' +
  '<file-upload ref="upload"  :input-id="\'uploadfile\'" :post-action="uploadurl" :accept="\'image/png,image/gif,image/jpeg,image/jpg\'" :headers="header" v-model="files" :multiple="multiple" :extensions="[\'jpg\', \'gif\', \'png\', \'jpeg\']" @input-file="inputFile">上传图片</file-upload>\n' +
  '</div></div></div>'
}
